import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import { resolve } from 'path';
import viteCompression from 'vite-plugin-compression';
import vueJsxPlugin from '@vitejs/plugin-vue-jsx';
import { createHash } from 'crypto';

// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const envConfig = loadEnv(mode, process.cwd(), 'Wind');
  return {
    plugins: [
      vue(),
      vueJsxPlugin(),
      viteCompression({
        verbose: true,
        disable: false,
        threshold: 10240,
        algorithm: 'gzip',
        ext: '.gz'
      })],
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '' +
            '@import "@/config/ui_config/application/variables/all_variables.scss";' +
            '@import "@/config/ui_config/application/mixin/all_mixin.scss";' +
            '@import "@/config/ui_config/element/variables/element_custom_variables.scss";'
        },
        modules: {
          generateScopedName: '[name]__[local]___[hash:base64:5]',
          hashPrefix: 'prefix'
        }
      }
    },
    assetsInclude: ['**/*.png', '**/*.jpg', '**/*.svg'],
    build: {
      sourcemap: true,
      chunkSizeWarningLimit: 2000,
      rollupOptions: {
        output: {
          entryFileNames: 'js/[name].[hash].js',
          chunkFileNames: chunkInfo => {
            if (chunkInfo.isDynamicEntry) {
              const hash = createHash('md5')
                .update(Object.values(chunkInfo.modules).map(m => m.code).join())
                .digest('hex');
              return 'js/[name].' + hash + '.js';
            } else {
              return 'js/[name].[hash].js';
            }
          },
          assetFileNames: 'assets/[ext]/[name][hash].[ext]',
          manualChunks (id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          }
        }
      }
    }
  };
});
